public class ThreadTest {

    public static void main(String[] args) {
        Resource r = new Resource();
        new Thread(new InputRe(r)).start();
        new Thread(new OutputRe(r)).start();
    }
}

//定义共享变量
class Resource {
    public String name;
    public char sex;
    //定义一个标记用于等待唤醒机制
    public boolean flag = false;
}

//输入线程类
class InputRe implements Runnable{

    private final Resource r;

    public InputRe(Resource r) {
        this.r = r;
    }

    int x;
    @Override
    public void run() {
        //一直循环打印
        while (true){
            //线程锁
            synchronized (r) {
                try {
                    //线程休眠
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //为false执行
                if (!r.flag){
                    if (x%2 == 0){
                        r.name = "马超";
                        r.sex = '男';
                    }else{
                        r.name = "小乔";
                        r.sex = '女';
                    }
                    x++;
                }
                //将标记改为true
                r.flag = true;
                //唤醒此监视器上等待的单个线程
                r.notify();
                try {
                    //此线程等待
                    r.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


//输出线程类
class OutputRe implements Runnable{
    private final Resource r;

    public OutputRe(Resource r) {
        this.r = r;
    }

    @Override
    public void run() {
        while (true){
            synchronized (r) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (r.flag){
                    System.out.println(r.name + r.sex);
                }
                r.flag = false;
                r.notify();
                try {
                    r.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}